const express = require('express');
const router = express.Router();
const rds = require('../rds.js');
const QRCode = require('qrcode');
const { createCanvas, loadImage } = require('canvas');
const fs = require('fs');
const path = require('path');
const axios = require('axios');

// 获取小程序模块配置
const weappModules = require('../data/weapp-modules.json');
const wework = require('../wework.js');

// BCH2501海报页面路由
router.get('/bch2501', async (req, res) => {
    try {
        const uid = req.session.totemUID || 1; // 默认使用1作为示例
        const moduleView = 'bch2501'; // 固定使用bch2501模块
        const backgroundUrl = 'https://totemlife.cn/apps/public/bch2501-poster-background.png'; // 固定背景图
        const params = `cid=${uid}`; // 使用当前用户的uid作为cid参数

        // 生成二维码的URL
        const qrcodeUrl = `https://totemlife.cn/apps/go-to-weapp?view=${moduleView}&${params}`;

        // 生成提示文字
        const tipText = `${moduleView}-${2025 + parseInt(uid)}`;

        // 获取是否使用小程序码，默认为true
        const useWxacode = req.query.useWxacode !== 'false';

        // 生成海报图片
        const posterBuffer = await generatePoster(backgroundUrl, qrcodeUrl, tipText, useWxacode);

        // 将图片转为base64
        const base64Image = posterBuffer.toString('base64');
        const posterImage = `data:image/png;base64,${base64Image}`;

        res.render('tools/bch2501-poster', {
            title: 'BCH2501海报',
            posterImage,
            qrcodeUrl,
            uid,
            useWxacode
        });
    } catch (error) {
        console.error('渲染BCH2501海报页面错误:', error);
        res.status(500).send('服务器错误');
    }
});

// BCH2501海报直接生成路由（用于下载）
router.get('/bch2501-poster/download', async (req, res) => {
    try {
        const uid = req.session.totemUID || 1; // 默认使用1作为示例
        const moduleView = 'bch2501'; // 固定使用bch2501模块
        const backgroundUrl = 'https://totemlife.cn/apps/public/bch2501-poster-background.png'; // 固定背景图
        const params = `cid=${uid}`; // 使用当前用户的uid作为cid参数

        // 生成二维码的URL
        const qrcodeUrl = `https://totemlife.cn/apps/go-to-weapp?view=${moduleView}&${params}`;

        // 生成提示文字
        const tipText = `${moduleView}-${2025 + parseInt(uid)}`;

        // 获取是否使用小程序码，默认为true
        const useWxacode = req.query.useWxacode !== 'false';

        // 生成海报图片
        const posterBuffer = await generatePoster(backgroundUrl, qrcodeUrl, tipText, useWxacode);

        // 设置响应头
        res.setHeader('Content-Type', 'image/png');
        res.setHeader('Content-Disposition', 'attachment; filename=bch2501-poster.png');

        // 发送图片数据
        res.send(posterBuffer);
    } catch (error) {
        console.error('生成BCH2501海报错误:', error);
        res.status(500).send('生成海报失败');
    }
});

// 用户信息显示路由
router.get('/user-info', async (req, res) => {
    try {
        const uid = req.session.totemUID || 1; // 默认使用1作为示例

        // 从数据库获取用户信息
        const query = `
            SELECT uid, real_name, avatar, roles, integral, now_money
            FROM tutem_mall.eb_user
            WHERE uid = ?
        `;

        const [[userInfo]] = await rds.query(query, [uid]);

        if (!userInfo) {
            return res.status(404).send('用户信息未找到');
        }

        res.render('tools/user-info', {
            title: '用户信息',
            userInfo
        });
    } catch (error) {
        console.error('获取用户信息错误:', error);
        res.status(500).send('服务器错误');
    }
});

// 海报生成页面路由
router.get('/poster', async (req, res) => {
    try {
        const uid = req.session.totemUID || 1; // 默认使用1作为示例
        const backgroundUrl = req.query.bg || '';
        const moduleView = req.query.view || '';
        // 默认使用小程序码，除非明确指定不使用
        const useWxacode = req.query.useWxacode !== 'false';

        // 获取可用的模块列表
        const modules = Object.keys(weappModules.paths).map(key => ({
            key,
            name: key,
            description: weappModules.paths[key].description
        }));

        res.render('tools/poster', {
            title: '海报生成工具',
            uid,
            backgroundUrl,
            moduleView,
            modules,
            defaultParams: `cid=${uid}`,
            useWxacode
        });
    } catch (error) {
        console.error('海报生成页面错误:', error);
        res.status(500).send('服务器错误');
    }
});

// 根据关键字搜索背景图
router.get('/poster/search-background', async (req, res) => {
    try {
        const keyword = req.query.keyword || '';

        if (!keyword) {
            return res.json({ success: false, message: '请输入关键字' });
        }

        // 从eb_system_attachment表中搜索匹配的图片
        const query = `
            SELECT att_id, title, att_dir, att_size, att_type 
            FROM eb_system_attachment 
            WHERE title LIKE ? AND att_type LIKE 'image/%'
            LIMIT 10
        `;

        const [results] = await rds.query(query, [`%${keyword}%`]);

        res.json({
            success: true,
            images: results.map(img => ({
                id: img.att_id,
                title: img.title,
                url: img.att_dir,
                size: img.att_size,
                type: img.att_type
            }))
        });
    } catch (error) {
        console.error('搜索背景图错误:', error);
        res.json({ success: false, message: '搜索失败' });
    }
});

// 生成海报
router.post('/poster/generate', async (req, res) => {
    try {
        const { backgroundUrl, moduleView, moduleParams, useWxacode } = req.body;
        const uid = req.session.totemUID || 1;

        if (!backgroundUrl) {
            return res.json({ success: false, message: '请选择背景图' });
        }

        if (!moduleView) {
            return res.json({ success: false, message: '请选择小程序模块' });
        }

        // 确保参数中包含cid
        let params = moduleParams || '';
        if (!params.includes('cid=')) {
            params = params ? `${params}&cid=${uid}` : `cid=${uid}`;
        }

        // 生成二维码的URL
        const qrcodeUrl = `https://totemlife.cn/apps/go-to-weapp?view=${moduleView}&${params}`;

        // 提取cid值用于生成提示文字
        let cid = uid;
        const cidMatch = params.match(/cid=(\d+)/);
        if (cidMatch && cidMatch[1]) {
            cid = parseInt(cidMatch[1]);
        }

        // 生成提示文字
        const tipText = `${moduleView}-${2025 + parseInt(cid)}`;

        // 生成海报图片
        const posterBuffer = await generatePoster(backgroundUrl, qrcodeUrl, tipText, useWxacode === 'true');

        // 将图片转为base64
        const base64Image = posterBuffer.toString('base64');

        res.json({
            success: true,
            posterImage: `data:image/png;base64,${base64Image}`,
            qrcodeUrl
        });
    } catch (error) {
        console.error('生成海报错误:', error);
        res.json({ success: false, message: '生成海报失败' });
    }
});

// 生成海报图片
async function generatePoster(backgroundUrl, qrcodeUrl, tipText, useWxacode = false) {
    // 创建画布 (默认尺寸 720x1280)
    const canvas = createCanvas(720, 1280);
    const ctx = canvas.getContext('2d');

    try {
        // 加载背景图
        const backgroundImage = await loadImage(backgroundUrl);

        // 计算背景图的缩放比例，确保填满画布
        const scale = Math.max(
            canvas.width / backgroundImage.width,
            canvas.height / backgroundImage.height
        );

        // 计算缩放后的尺寸
        const scaledWidth = backgroundImage.width * scale;
        const scaledHeight = backgroundImage.height * scale;

        // 计算居中位置
        const x = (canvas.width - scaledWidth) / 2;
        const y = (canvas.height - scaledHeight) / 2;

        // 绘制背景图
        ctx.drawImage(backgroundImage, x, y, scaledWidth, scaledHeight);

        // 二维码尺寸
        const qrcodeSize = 176;
        let qrcodeCanvas;

        if (useWxacode) {
            // 生成小程序码
            qrcodeCanvas = await generateWxacode(qrcodeUrl, qrcodeSize);
        } else {
            // 生成普通二维码
            qrcodeCanvas = createCanvas(qrcodeSize, qrcodeSize);
            await QRCode.toCanvas(qrcodeCanvas, qrcodeUrl, {
                errorCorrectionLevel: 'H',
                margin: 1,
                width: qrcodeSize
            });
        }

        // 在右下角绘制二维码或小程序码
        const qrcodeX = canvas.width - qrcodeSize - 10;
        const qrcodeY = canvas.height - qrcodeSize - 70;
        ctx.drawImage(qrcodeCanvas, qrcodeX, qrcodeY, qrcodeSize, qrcodeSize);

        // 在二维码下方添加提示文字
        ctx.font = 'bold 20px Arial';
        ctx.fillStyle = '#FFFFFF';
        ctx.textAlign = 'center';

        // 添加文字背景
        const textWidth = ctx.measureText(tipText).width;
        ctx.fillStyle = 'rgba(0, 0, 0, 0.6)';
        ctx.fillRect(
            qrcodeX + (qrcodeSize - textWidth) / 2 - 10,
            qrcodeY + qrcodeSize + 5,
            textWidth + 20,
            30
        );

        // 添加文字
        ctx.fillStyle = '#FFFFFF';
        ctx.fillText(tipText, qrcodeX + qrcodeSize / 2, qrcodeY + qrcodeSize + 25);

        // 将画布转换为Buffer
        return canvas.toBuffer('image/png');
    } catch (error) {
        console.error('生成海报图片错误:', error);
        throw error;
    }
}

// 生成小程序码
async function generateWxacode(qrcodeUrl, size) {
    try {
        // 解析URL参数
        const url = new URL(qrcodeUrl);
        const params = new URLSearchParams(url.search);

        // 获取view和cid参数
        const view = params.get('view');
        const cid = params.get('cid');

        if (!view) {
            throw new Error('缺少view参数');
        }

        // 获取小程序路径信息
        const moduleInfo = weappModules.paths[view];
        if (!moduleInfo) {
            throw new Error(`未找到模块: ${view}`);
        }

        // 构建小程序路径
        let path = moduleInfo.path;

        // 添加额外参数
        const queryParams = [];
        if (cid) {
            //queryParams.push(`cid=${cid}`);
            queryParams.push(`spreader_uid=${cid}`);
        }

        // 添加模块特定的额外参数
        if (moduleInfo.additionalParams && Object.keys(moduleInfo.additionalParams).length > 0) {
            for (const [key, value] of Object.entries(moduleInfo.additionalParams)) {
                if ( key === 'url' ) {
                    const url = encodeURIComponent(value.includes('?') ? `${value}&rft=${cid}` : `${value}?rft=${cid}`);
                    queryParams.push(`${key}=${url}`);
                } else {
                    queryParams.push(`${key}=${encodeURIComponent(value)}`);
                }
            }
        }

        // 组合完整路径
        if (queryParams.length > 0) {
            path = `${path}?${queryParams.join('&')}`;
        }

        // 获取小程序访问令牌
        const accessToken = await wework.getWechatAccessToken('weapp');
        console.log('generate miniProgram path:', path);

        // 调用微信API生成小程序码
        const response = await axios({
            method: 'post',
            url: `https://api.weixin.qq.com/wxa/getwxacode?access_token=${accessToken}`,
            data: {
                path: path,
                width: size,
                auto_color: false,
                line_color: { r: 0, g: 0, b: 0 },
                is_hyaline: false
            },
            responseType: 'arraybuffer'
        });

        // 将响应数据转换为Buffer
        const buffer = Buffer.from(response.data);

        // 检查是否返回了错误信息
        if (buffer.toString().indexOf('"errcode"') > -1) {
            const errorData = JSON.parse(buffer.toString());
            throw new Error(`生成小程序码失败: ${errorData.errmsg}`);
        }

        // 将Buffer转换为Canvas
        const image = await loadImage(buffer);
        const qrcodeCanvas = createCanvas(size, size);
        const ctx = qrcodeCanvas.getContext('2d');
        ctx.drawImage(image, 0, 0, size, size);

        return qrcodeCanvas;
    } catch (error) {
        console.error('生成小程序码错误:', error);
        // 如果生成小程序码失败，回退到普通二维码
        const qrcodeCanvas = createCanvas(size, size);
        await QRCode.toCanvas(qrcodeCanvas, qrcodeUrl, {
            errorCorrectionLevel: 'H',
            margin: 1,
            width: size
        });
        return qrcodeCanvas;
    }
}

// 兼容性保留
router.get('/abc-scale', async (req, res) => {
    res.redirect('/apps/scales/abc-scale');
});
router.get('/gsrs-scale', async (req, res) => {
    res.redirect('/apps/scales/gsrs-scale');
});
router.get('/scales-dashboard', async (req, res) => {
    res.redirect('/apps/scales/scales-dashboard');
});

module.exports = router;
